package com.corning.common.aop;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class BeforPoint {

    @Pointcut("execution(* com.corning.*.controller.*.*(..))")
    public void point(){
        log.info("======================AOP===================");
    }

    @Before("point()")
    public void beforePoint(){
        // 获取RequestAttributes

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        log.info("URL:{}",request.getRequestURI().toString());
    }
    @AfterThrowing(value = "execution(* com.corning.*.controller.*.*(..))",throwing = "ex")
    public void throwing(Exception ex){
        // 获取RequestAttributes

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        log.info("URL:{}",request.getRequestURI().toString(),ex.getMessage());
    }

    @Around("execution(* com.corning.*.controller.*.*(..))")
    public Object around(ProceedingJoinPoint pjp){
        System.out.println("环绕通知执行了");

        log.info("Request Args   : {}", new Gson().toJson(pjp.getArgs()));
        Object[] args = pjp.getArgs();
        try {
            return pjp.proceed(args);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }

    }

}
